package com.picture.download.controller;

import com.picture.download.Settings;
import com.picture.download.entity.Images;
import com.picture.download.util.ResponseUtil;
import com.picture.download.util.Utils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.lang.Strings;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by chenjidong on 2015/4/22.
 */
@At("/images")
public class ImagesController {
    private static Dao dao = Settings.getDao();

    @At
    @Ok("json")
    @POST
    public Object get(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize, @Param("::filter") Map<String, String> filter, @Param("::sort") List<String> sort) {
        if (pageNum == null || pageNum == 0) pageNum = 1;
        if (pageSize == null || pageSize == 0) pageSize = 20;

        Pager pager = dao.createPager(pageNum, pageSize);
        Criteria cri = Utils.setupFilter(Cnd.cri(), filter, sort);

        List<Images> list = dao.query(Images.class, cri, pager);
        pager.setRecordCount(dao.count(Images.class, cri));

        return ResponseUtil.response(0, "", list);
    }

    @At
    @GET
    @Ok("json")
    public Object setPraise(@Param("oid") String oid,HttpServletRequest request) {
        String msg = "";
        if (null == oid || Strings.equals("", oid)) {
            msg += "图片不存在！\n";

        } else {
            Images images = dao.fetch(Images.class, Cnd.where("oid", "=", oid));
            if (null != images) {
                int oldPraise = images.getPraise();
                images.setPraise(oldPraise + 1);
                dao.update(images);
            }
        }
        if (!Strings.equals("", msg)) {
            return ResponseUtil.response(1, msg, "");
        }
        return ResponseUtil.response(0, "", "");
    }
}
